/**   
* @Title: DynamicDataSourceAnnotationAdvisor.java
* @Package org.xaoyaoyao.cloud.dynamic.aop
* @Description: TODO
* @author xaoyaoyao
* @date Jul 3, 2019 4:10:49 PM
* @version V1.0   
*/
package org.xaoyaoyao.cloud.dynamic.aop;

import org.aopalliance.aop.Advice;
import org.springframework.aop.Pointcut;
import org.springframework.aop.support.AbstractPointcutAdvisor;
import org.springframework.aop.support.ComposablePointcut;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.xaoyaoyao.cloud.dynamic.annotation.DynamicDataSource;

/**
 * @ClassName: DynamicDataSourceAnnotationAdvisor
 * @Description: TODO
 * @author xaoyaoyao
 * @date Jul 3, 2019 4:10:49 PM
 * 
 */
public class DynamicDataSourceAnnotationAdvisor extends AbstractPointcutAdvisor implements BeanFactoryAware {

	private Advice advice;

	private Pointcut pointcut;

	public DynamicDataSourceAnnotationAdvisor(DynamicDataSourceAnnotationInterceptor dynamicDataSourceAnnotationInterceptor) {
		this.advice = dynamicDataSourceAnnotationInterceptor;
		this.pointcut = buildPointcut();
	}

	@Override
	public Pointcut getPointcut() {
		return this.pointcut;
	}

	@Override
	public Advice getAdvice() {
		return this.advice;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		if (this.advice instanceof BeanFactoryAware) {
			((BeanFactoryAware) this.advice).setBeanFactory(beanFactory);
		}
	}

	private Pointcut buildPointcut() {
		Pointcut cpc = (Pointcut) new AnnotationMatchingPointcut(DynamicDataSource.class, true);
		// 类注解
		Pointcut clpc = (Pointcut) AnnotationMatchingPointcut.forClassAnnotation(DynamicDataSource.class);
		// 方法注解
		Pointcut mpc = (Pointcut) AnnotationMatchingPointcut.forMethodAnnotation(DynamicDataSource.class);
		return new ComposablePointcut(cpc).union(clpc).union(mpc);
	}

}
